<?php

namespace App\Http\Controllers\Invoice\Merchant;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Invoice\InvoiceHeaderValidate;
use App\Service\Invoice\Merchant\InvoiceHeaderService;
use App\Models\Invoice\InvoiceHistoryModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class InvoiceHeaderManageController extends BaseController
{

    /** 获取默认的发票抬头
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws \Exception
     */
    public function getDefaultInfo(Request $request): JsonResponse
    {
        $shopId  = (int)$request->header('shopId');
        $brandId = (int)$request->header('brandId');
        $userId  = getRmsUserId();

        return $this->success(InvoiceHeaderService::getDefaultShopInfo($userId, $shopId));

    }

    /** 更新抬头
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws \Exception
     */
    public function update(Request $request, $id): JsonResponse
    {
        $param  = $request->post();
        $shopId = (int)$request->header('shopId');

        // 公共参数验证
        InvoiceHeaderValidate::updateValidate($request->merge(["id" => $id])->all());
        if ($param['headerType'] == InvoiceHistoryModel::HEADER_TYPE_1) {
            if ($param['invoiceType'] == InvoiceHistoryModel::INVOICE_TYPE_1) {

                // 专票验证
                InvoiceHeaderValidate::updateSpecialValidate($request->merge(["id" => $id])->all());
            } else {

                // 普票验证
                InvoiceHeaderValidate::updateCommonValidate($request->merge(["id" => $id])->all());
            }
        } else {

            // 个人抬头名称只能用个人，普票
            $param["invoiceTitle"] = "个人";
            $param["invoiceType"]  = InvoiceHistoryModel::INVOICE_TYPE_0;
        }

        // 追加id
        $param['id']     = $id;
        $param['userId'] = request()->user()->id;
        $param['shopId'] = $shopId;

        InvoiceHeaderService::update($param);
        return $this->success();

    }


}
